package sun.demos.mrdemo.mr.run;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import sun.demos.mrdemo.mr.obj.StreamObj;

public class DataCount {

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        
        Job job = Job.getInstance(new Configuration());
        
        job.setJarByClass(DataCount.class);
        
        job.setMapperClass(DataCount.StreamMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(StreamObj.class);
        
        FileInputFormat.setInputPaths(job, new Path(args[0]));
        
        job.setReducerClass(DataCount.StreamReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(StreamObj.class);
        
        FileOutputFormat.setOutputPath(job, new Path(args[1]));
        
        job.waitForCompletion(true);
    }
    
    class StreamMapper extends Mapper<LongWritable, Text, Text, StreamObj>{

        @Override
        protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, StreamObj>.Context context)
                throws IOException, InterruptedException {
            
            String val = value.toString();
            
            String[] vals = val.split("\t");
            
            if(vals != null ){
                
                context.write(new Text(vals[0]), new StreamObj(vals[0], Long.parseLong(vals[8]), Long.parseLong(vals[9])));
            }
        }
        
        
    }
    
    class StreamReducer extends Reducer<Text, StreamObj, Text, StreamObj>{

        @Override
        protected void reduce(Text key, Iterable<StreamObj> values,
                Reducer<Text, StreamObj, Text, StreamObj>.Context context) throws IOException, InterruptedException {
        
            long inCount = 0;
            long outCount = 0;
            for (StreamObj obj : values) {
                
                inCount += obj.getInCount();
                outCount += obj.getOutCount();
            }
            
            context.write(key, new StreamObj(key.toString(), inCount, outCount));
            
        }
        
        
    }
}
